import { createStore } from 'vuex';
import { getCurrentUser, getUserInfo } from '@/api/auth';

const store = createStore({
  state: {
    token: localStorage.getItem('token') || null,
    user: null,
    role: localStorage.getItem('userRole') || null,
    isAuthenticated: !!localStorage.getItem('token')
  },
  getters: {
    isAuthenticated: state => state.isAuthenticated,
    currentUser: state => state.user,
    token: state => state.token,
    userRole: state => state.role,
    // 判断用户是否有管理员权限
    isAdmin: state => state.role && state.role !== '用户'
  },
  mutations: {
    SET_TOKEN(state, token) {
      state.token = token;
      state.isAuthenticated = !!token;
      localStorage.setItem('token', token);
    },
    SET_ROLE(state, role) {
      state.role = role;
      localStorage.setItem('userRole', role);
    },
    CLEAR_TOKEN(state) {
      state.token = null;
      state.isAuthenticated = false;
      localStorage.removeItem('token');
    },
    CLEAR_ROLE(state) {
      state.role = null;
      localStorage.removeItem('userRole');
    },
    SET_USER(state, user) {
      state.user = user;
    },
    CLEAR_USER(state) {
      state.user = null;
    },
    SET_USER_INFO(state, userInfo) {
      state.user = userInfo;
    }
  },
  actions: {
    async login({ commit, dispatch }, payload) {
      // 支持既可以传递字符串token，也可以传递包含token和role的对象
      if (typeof payload === 'object') {
        const { token, role, userId } = payload;
        console.log(payload);
        commit('SET_TOKEN', token);
        if (role) {
          commit('SET_ROLE', role);
        }
        if (userId) {
          localStorage.setItem('userId', userId);
        }
      } else {
        commit('SET_TOKEN', payload);
      }
      // 登录后获取用户信息
      await dispatch('fetchUserInfo');
    },
    logout({ commit }) {
      commit('CLEAR_TOKEN');
      commit('CLEAR_ROLE');
      commit('CLEAR_USER');
      localStorage.removeItem('userId');
    },
    async fetchUserInfo({ commit, state }) {
      try {
        const userId = state.user?.id || localStorage.getItem('userId');
        if (!userId) {
          throw new Error('用户ID不存在');
        }
        const response = await getUserInfo(userId);
        if (response.data.code === 200) {
          commit('SET_USER_INFO', response.data.data);
        } else {
          throw new Error(response.data.msg || '获取用户信息失败');
        }
      } catch (error) {
        console.error('获取用户信息失败:', error);
        throw error;
      }
    }
  }
});

export default store;